package com.nutrition.health.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * JSON 工具类
 * 用于处理 JSON 数据的转换
 */
public class JsonUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 将对象转换为 JSON 字符串
     * @param object 要转换的对象
     * @return JSON 字符串
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("Failed to convert object to JSON", e);
            return "{}";
        }
    }
    
    /**
     * 将 JSON 字符串转换为 Map
     * @param json JSON 字符串
     * @return Map 对象
     */
    public static Map<String, Object> fromJson(String json) {
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (JsonProcessingException e) {
            logger.error("Failed to parse JSON", e);
            return new HashMap<>();
        }
    }
    
    /**
     * 将 Map 转换为指定类型的对象
     * @param map Map 对象
     * @param clazz 目标类型
     * @param <T> 目标类型
     * @return 转换后的对象
     */
    public static <T> T fromMap(Map<String, Object> map, Class<T> clazz) {
        try {
            return objectMapper.convertValue(map, clazz);
        } catch (Exception e) {
            logger.error("Failed to convert map to object", e);
            return null;
        }
    }
}